#include "type.h"

char* substr(char* org, char* sub, int bytes)
{
	int i = 0, j = 0;
	for (i = 0; i < bytes; ++i)
	{
		if (org[i] == sub[j]) { ++j; }
		else { j = 0; }
		
		if (j == strlen(sub)) { return org + i - j; }
	}
	return 0;
}

void main(int argc, char* argv[])
{
	int i = 0, fd = -1, bytesRead = 0;
	char buf[128], *file, *pattern;
	
	do_write(2, "*****************************\n\r", 31);
	do_write(2, "*      JRR Grep Program     *\n\r", 31);
	do_write(2, "*****************************\n\r", 31);
	
	if (argc == 1 && contains(' ', argv[0]))
	{
		strtok(argv[0], " ");
		pattern = strtok(0, " ");
		file = pattern + strlen(pattern) + 1;
		fd = open(file, READ);
		do_write(2, "Reading from \"", 14);
		do_write(2, file, strlen(file));
		do_write(2, "\"\n\r", 3);
	}
	else if (argc == 2)
	{
		fd = 0;
		pattern = argv[1];
		do_write(2, "Reading from stdin\n\r", 20);
	}
	else if (argc == 3)
	{
		fd = open(argv[2], READ);
		pattern = argv[1];
		file = argv[2];
		do_write(2, "Reading from \"", 14);
		do_write(2, argv[2], strlen(argv[2]));
		do_write(2, "\"\n\r", 3);
	}
	else
	{
		printf("Usage: grep pattern filename\n");
		return;
	}
	
	if (fd > -1)
	{
		while (1)
		{
			i = 0;
			do
			{
				bytesRead = do_read(fd, &buf[i], 1);
				if (buf[i++] == '\n') { break; }
			} while (bytesRead == 1);
			
			if (bytesRead == 0) { return; }
			
			if (substr(buf, pattern, i) != 0)
			{
				do_write(1, buf, i);
				printf("\r");
			}
		}
	}
	else
	{
		printf("Unable to open \"%s\"!\n", file);
	}
}
